package com.jiaquyun.jcyx.main.user

import android.Manifest
import android.annotation.SuppressLint
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.app.AppConstance
import com.jiaquyun.jcyx.jetpack.mode.UserViewModel
import com.jiaquyun.jcyx.main.mine.MineRichTextActivity
import com.jiaquyun.jcyx.popup.DialogProtocolPopup
import com.module.lemlin.LoadingDialog
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeFragment
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_access_login.*
import java.util.concurrent.TimeUnit

class LoginFragment : OwnerViewModeFragment<UserViewModel>() {

    companion object {
        fun newInstance(): LoginFragment {
            return LoginFragment()
        }
    }


    private val protocolHintPopup: DialogProtocolPopup by lazy {
        DialogProtocolPopup(context,
            onConfirm = {
                protocolContentPopup.setContentText().showPopupWindow()
                protocolHintPopup.dismiss()
            },
            onCancel = {

                cbAccessSelect.isChecked = false
                protocolHintPopup.dismiss()
                ActivityUtils.finishAllActivities()
            },
            onProtocol = { title, content ->

            })
    }
    private val protocolContentPopup: DialogProtocolPopup by lazy {
        DialogProtocolPopup(context,
            onConfirm = {
//                SPStaticUtils.put(AppConstance.KEY_NAME_PROTOCOL, true)
                protocolContentPopup.dismiss()
//                viewModel.videoNoReward()
                cbAccessSelect.isChecked = true
            },
            onCancel = {
//                SPStaticUtils.put(AppConstance.KEY_NAME_PROTOCOL, false)
                protocolContentPopup.dismiss()
                protocolHintPopup.setHintText().showPopupWindow()
            },
            onProtocol = { title, id ->
                val activity = this@LoginFragment.activity
                    ?: return@DialogProtocolPopup
                MineRichTextActivity.openId(activity = activity, title = title, id = id)
            })
    }

    override val layoutResId: Int
        get() = R.layout.fragment_access_login

    override fun viewModel(): UserViewModel {
        return createViewModel()
    }

    override fun initView() {

        val isAgree: Boolean =
            SPStaticUtils.getBoolean(AppConstance.KEY_NAME_PROTOCOL, (false))
        if (!isAgree) {
            protocolContentPopup.setContentText().showPopupWindow()
        }

        etLoginCodePhone.addTextChangedListener {
            tvLoginSubmit.isEnabled = !it.isNullOrEmpty()
                    && !etLoginCodeCode.text.isNullOrEmpty()
            tvLoginCodeGet.isEnabled = !it.isNullOrEmpty()
                    && it.length == 11
        }

        etLoginCodeCode.addTextChangedListener {
            tvLoginSubmit.isEnabled = !it.isNullOrEmpty()
                    && !etLoginCodePhone.text.isNullOrEmpty()
        }

        tvLoginCodeGet.setOnClickListener {
            viewModel.smsSend(etLoginCodePhone.text.toString(), "mobilelogin")
        }

        tvLoginSubmit.setOnClickListener {
            if (cbAccessSelect.isChecked) {
                viewModel.userMobileLogin(
                    etLoginCodePhone.text.toString(),
                    etLoginCodeCode.text.toString()
                )
            } else {
                protocolContentPopup.setContentText().showPopupWindow()
            }
        }

        cbAccessSelect.setOnCheckedChangeListener { buttonView, isChecked ->
            SPStaticUtils.put(AppConstance.KEY_NAME_PROTOCOL, isChecked)
        }
        tvAccessUserAgree.setOnClickListener {
            val activity = this@LoginFragment.activity
                ?: return@setOnClickListener
            MineRichTextActivity.openId(activity = activity, title = "用户协议", id = 1)
        }
        tvAccessSecrecyAgree.setOnClickListener {
            val activity = this@LoginFragment.activity
                ?: return@setOnClickListener
            MineRichTextActivity.openId(activity = activity, title = "隐私政策", id = 5)
        }

    }


    override fun initViewMode() {
        viewModel.smsLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.START) {
                LoadingDialog.show(requireContext(), R.layout.dialog_load_style_1)
            } else {
                LoadingDialog.dismiss()
            }
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            codeDownTime(tvLoginCodeGet)
        })// {"code":1,"msg":"发送成功","time":"1613973913","data":{"is_new":false}}

        viewModel.loginLiveDate.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.START) {
                LoadingDialog.show(requireContext(), R.layout.dialog_load_style_1)
            } else {
                LoadingDialog.dismiss()
            }
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
//            requireActivity().finish()
            ActivityUtils.finishActivity(AccessActivity::class.java)
        })//{"code":1,"msg":"登录成功","time":"1613973943","data":{"userinfo":{"id":2499,"nickname":"森林狂想","mobile":"18396125445","avatar":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/wJntJNuf18gTPp719eFEMAOcibDTELyoJYqXicoDqeRqxRUeic9aFwOC0icbnO5us4mbkWMKIe0Aia9C7CefbH9VO3w\/132","card_type":"","money":"0.00","is_new":1,"chat_id":"0","token":"6fa1c895-2b10-490e-9805-b00a4a545088","user_id":2499,"createtime":1613973943,"expiretime":1616565943,"expires_in":2592000},"isNew":false}}
    }

    /**
     * 获取验证码倒计时
     * */
    @SuppressLint("SetTextI18n")
    private fun codeDownTime(view: TextView) {
        val disposable: Disposable = Flowable.intervalRange(1, 60, 0, 1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext {
                val num: Long = 60 - it
                view.text = if (num < 10) {
                    "剩余0${num}秒"
                } else "剩余${num}秒"
            }
            .doOnSubscribe {
                view.isEnabled = false
            }
            .doOnComplete {
                view.text = "获取验证码"
                view.isEnabled = true
            }
            .subscribe()
        viewModel.dispose.add(disposable)
    }
}